import 'package:elephant_fish/http/core/hi_error.dart';
import 'package:elephant_fish/http/core/hi_net.dart';
import 'package:elephant_fish/http/request/base_request.dart';
import 'package:elephant_fish/http/request/room_request.dart';
import 'package:elephant_fish/model/room_classify_entity.dart';
import 'package:elephant_fish/model/room_entity.dart';
import 'package:elephant_fish/page/index_skill_page.dart';
import 'package:elephant_fish/util/TxUtils.dart';
import 'package:elephant_fish/widget/index_slide_banner.dart';
import 'package:elephant_fish/widget/slide_banner.dart';
import 'package:elephant_fish/widget/video_card.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'index_follow_page.dart';
import 'login_page.dart';

class IndexHotPage extends StatefulWidget {
  final int categoryName;
  final List<Children> list;
  const IndexHotPage({Key key, this.categoryName, this.list}) : super(key: key);

  @override
  _IndexHotPageState createState() => _IndexHotPageState();
}

class _IndexHotPageState extends State<IndexHotPage>
    with AutomaticKeepAliveClientMixin {
  List<RoomEntity> roomList = [];
  int pageIndex = 1;
  bool _loading = false;
  ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      var dis = _scrollController.position.maxScrollExtent -
          _scrollController.position.pixels;
      //当距离底部不足300时加载更多
      if (dis < 300 && !_loading) {
        _loadData(loadMore: true);
      }
    });
    _loadData();
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xff140c3c),
      body: Column(
        children: [
          SingleChildScrollView(child: IndexSlideBanner()),
          SizedBox(height: 20,),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Column(
                children: [
                  InkWell(
                    child:  Image.asset('assets/images/qianli.png',width: 50,height: 50,),
                    onTap: (){
                      showSecondVideo('潜力新星');
                    },
                  ),
                  SizedBox(height: 6,),
                  Text('潜力新星',style: TextStyle(color: Color(0xffffffff),fontSize: 12),)
                ],
              ),
              SizedBox(width: 41.5,),
              Column(
                children: [
                  InkWell(
                    child:  Image.asset('assets/images/banzhuan.png',width: 50,height: 50,),
                    onTap: (){
                      showSecondVideo('搬砖能手');
                    },
                  ),
                  SizedBox(height: 6,),
                  Text('搬砖能手',style: TextStyle(color: Color(0xffffffff),fontSize: 12),)
                ],
              ),
              SizedBox(width: 41.5,),
              Column(
                children: [
                  InkWell(
                    child:  Image.asset('assets/images/toutiao.png',width: 50,height: 50,),
                    onTap: (){
                      showSecondVideo('头条主播');
                    },
                  ),
                  SizedBox(height: 6,),
                  Text('头条主播',style: TextStyle(color: Color(0xffffffff),fontSize: 12),)
                ],
              ),
              SizedBox(width: 41.5,),
              Column(
                children: [
                  InkWell(
                    child:  Image.asset('assets/images/daren.png',width: 50,height: 50,),
                    onTap: (){
                      showSecondVideo('达人主播');
                    },
                  ),
                  SizedBox(height: 6,),
                  Text('达人主播',style: TextStyle(color: Color(0xffffffff),fontSize: 12),)
                ],
              ),
            ],
          ),
          SizedBox(height: 24.5,),
          Expanded(
            child: EasyRefresh(
              header: ClassicalHeader(
                refreshText: '下拉刷新',
                refreshReadyText: '准备刷新数据',
                refreshingText: '正在刷新中...',
                refreshedText: '刷新完成',
                textColor: Colors.white,
                showInfo: false,
              ),
              emptyWidget: roomList.length <= 0
                  ? Center(
                      child: Text(
                        "暂无视频互动直播间",
                        style: TextStyle(color: Colors.white),
                      ),
                    )
                  : null,
              onRefresh: () async {
                print('onRefresh');
                _refreshData();
              },
              child: StaggeredGridView.countBuilder(
                  shrinkWrap: true,
                  controller: _scrollController,
                  physics: const AlwaysScrollableScrollPhysics(),
                  padding: EdgeInsets.only(left: 3, right: 3, top: 3),
                  crossAxisCount: 4,
                  crossAxisSpacing: 4,
                  itemCount: roomList.length,
                  itemBuilder: (BuildContext context, int index) {
                    //有banner时第一个item位置显示banner
                    return VideoCard(roomEntity: roomList[index]);
                  },
                  staggeredTileBuilder: (int index) {
                    return StaggeredTile.fit(2);
                  }),
            ),
          )
        ],
      ),
    );
  }

  void _loadData({loadMore = false}) async {
    _loading = true;
    if (!loadMore) {
      pageIndex = 1;
    }
    var currentIndex = pageIndex + (loadMore ? 1 : 0);
    print('loading:currentIndex:$currentIndex');
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String appToken = prefs.getString('app-token');
      BaseRequest request = RoomRequest();
      request
          .add('page', currentIndex)
          .add('classify_id', widget.categoryName)
          .add('type', 2)
          .addHeader('usertoken', appToken);
      var result = await HiNet.getInstance().fire(request);
      if (result['code'] == -1) {
        TxUtils.showErrorToast('登录失效，请重新登录', context);
        Navigator.pop(context);
        Navigator.of(context).push(MaterialPageRoute(
          builder: (context) {
            return LoginPage(
              arguments: {'loginCode': '-1'},
            );
          },
        ));
      } else if (result['code'] == 0) {
        List<Map<String, dynamic>> listMap =
            new List<Map<String, dynamic>>.from(result['data']['data']);
        List<RoomEntity> list = List();
        for (int i = 0; i < listMap.length; i++) {
          list.add(RoomEntity.fromJson(listMap[i]));
        }
        setState(() {
          if (loadMore) {
            if (list.isNotEmpty) {
              //合成一个新数组
              roomList = [...roomList, ...list];
              pageIndex++;
            }
          } else {
            roomList = list;
          }
        });
        Future.delayed(Duration(milliseconds: 1000), () {
          _loading = false;
        });
      }
    } on NeedAuth catch (e) {
      print(e);
    } on HiNetError catch (e) {
      print(e);
    }
  }

  void _refreshData() async {
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String appToken = prefs.getString('app-token');
      BaseRequest request = RoomRequest();
      request
          .add('classify_id', widget.categoryName)
          .add('type', 2)
          .addHeader('usertoken', appToken);
      var result = await HiNet.getInstance().fire(request);
      if (result['code'] == -1) {
        TxUtils.showErrorToast('登录失效，请重新登录', context);
        Navigator.pop(context);
        Navigator.of(context).push(MaterialPageRoute(
          builder: (context) {
            return LoginPage(
              arguments: {'loginCode': '-1'},
            );
          },
        ));
      } else if (result['code'] == 0) {
        List<Map<String, dynamic>> listMap =
        new List<Map<String, dynamic>>.from(result['data']['data']);
        List<RoomEntity> list = List();
        for (int i = 0; i < listMap.length; i++) {
          list.add(RoomEntity.fromJson(listMap[i]));
        }
        setState(() {
            roomList = list;
        });
      }
    } on NeedAuth catch (e) {
      print(e);
    } on HiNetError catch (e) {
      print(e);
    }
  }


  @override
  bool get wantKeepAlive => true;

  void showSecondVideo(String s) {
    for(int i = 0 ; i < widget.list.length ; i ++){
      if(widget.list[i].name == s){
        Navigator.of(context).push(MaterialPageRoute(
            builder: (context) => IndexFollowPage(
              categoryName: widget.list[i].name,categoryNum: widget.list[i].id,
            )));
      }
    }
  }
}
